#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <fcntl.h>

// g++ non_block.cc -o non_block -std=c++11

using namespace std;

// 设置非阻塞
void set_non_block(int fd)
{
    // 获取fd信息
    int fl = fcntl(fd, F_GETFL);
    if(fl == -1) perror("fl err");

    // 设置非阻塞
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    char buffer[64];
    set_non_block(0);
    while(1)
    {
        printf("read:");
        fflush(stdout);
        //ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        ssize_t n = read(4, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n - 1] = 0;
            cout << buffer << endl;
        }
        else if(n == 0)
        {
            cout << "end file" << endl;
        }
        else
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                // 底层数据未就绪
                cout << "底层数据未就绪" << endl;
                sleep(1);
                continue;
            }
            else if(errno == EINTR)
            {
                // 这次IO被信号中断
                continue;
            }
            else
            {
                cout << "err code:" << errno << endl;
                perror("read file err");
                break;
            }
        }
    }
    return 0;
}